<?php

namespace app\api\controller;

use app\admin\model\Area;
use app\admin\model\commission\Log;
use app\admin\model\CouponRecord;
use app\admin\model\Details;
use app\admin\model\order\Operations;
use app\admin\model\Products;
use app\admin\model\SystemConfig;
use app\admin\model\Worktags;
use app\api\middleware\RoleCheck;
use app\api\service\OrderService;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Db;
use think\Hook;
use think\Request;
use think\Validate;

/**
 * 技师列表
 */
class Rider extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /*
     * 技师列表
     */
    public function rider_list()
    {

        $latitude = input('latitude');
        $longitude = input('longitude');

        $Common = new Common();
        $response = $Common->getLocation($latitude, $longitude);
        $responseData = json_decode($response->getContent(), true);

        $city_id= Area::where('name','=',$responseData['data']['city'])->value('id');


        if(!$city_id){
            $this->error('地址不存在');
        }
        $latitude = input('latitude');
        $name = input('name');
        $longitude = input('longitude');
        $query = Db::name('user_details')->alias('ml')
            ->where('login_status', '=', '正常')
            ->where('role', '=', 'companion')
            ->where('city', '=', $city_id)
            ->whereNotNull('user_id')
            ->where('name', 'like', '%' . $name . '%')
            ->where('longitude', '<>', '')->where('latitude', '<>', '')
            ->field("id,exp_years,img,job_tags,lev,name,age,intro,work_experience,(6378.138 * 2 * asin(sqrt(pow(sin((latitude * pi() / 180 - " . $latitude . " * pi() / 180) / 2),2) + cos(latitude * pi() / 180) * cos(" . $latitude . " * pi() / 180) * pow(sin((longitude * pi() / 180 - " . $longitude . " * pi() / 180) / 2),2))) * 1000) as distance")
            ->order('distance');

        // 如果 $name 有值，则添加模糊查询条件
        if (!empty($name)) {
            $query->where('name', 'like', '%' . $name . '%');
        }
        $list = $query->paginate(20)->toArray();
        foreach ($list['data'] as $k => $v) {
            $list['data'][$k]['distance'] = round($v['distance'] / 1000, 2) . 'Km';
            $list['data'][$k]['job_tags'] = Worktags::where('id', 'in', $v['job_tags'])->field('id,name')->select();
        }
        $this->success('请求成功', $list);
    }
    /*
     * 技师详情
     */

    public function rider_details()
    {
        if (!$id = input('id')) {
            $this->error('请选择陪伴师');
        }

        $latitude = input('latitude');
        $longitude = input('longitude');
        $details = Db::name('user_details')->alias('ml')
            ->where('id', '=', $id)
            ->field("lev,id,profile_image,price,job_tags,name,age,intro,work_experience,certificate,work_experience,interests,edu,exp_years,IFNULL((select name from fa_area where id=province),'') province,IFNULL((select name from fa_area where id=city),'') city,IFNULL((select name from fa_area where id=district),'') district,(6378.138 * 2 * asin(sqrt(pow(sin((latitude * pi() / 180 - " . $latitude . " * pi() / 180) / 2),2) + cos(latitude * pi() / 180) * cos(" . $latitude . " * pi() / 180) * pow(sin((longitude * pi() / 180 - " . $longitude . " * pi() / 180) / 2),2))) * 1000) as distance")
            ->order('distance')
            ->find();
        if($details){
            $details['distance']=round($details['distance']/1000,2).'Km';
            $details['job_tags']=Worktags::where('id','in',$details['job_tags'])->field('id,name')->select();
        }
        //解析图片
        $details['certificate']=explode(",", $details['certificate']);

        $details['profile_image']=explode(",", $details['profile_image']);
        $sys=SystemConfig::find();
        $details['callphone']=$sys['hotline'];
        $this->success('请求成功',$details);
    }


    public function CheckRole(){


        $a=1;
    }

    /*
   * 陪伴师--确认到达
   */
    public function verifyarrival(){

        $a=input('id');
        if(!$id= input('id')){
            $this->error('请选择订单');
        }
        $detail= RoleCheck::role($this->auth->id,'companion');

        $result = \app\admin\model\Order::where('id','=',$id)->where('is_reach','=',0)->where('order_status','=',1)->where('riderid','=',$detail['id'])->update(['is_reach'=>1]);
        if($result>0){
            Operations::create([
                'order_id' => $id,
                'action' => '确认到达',
                'user_id' =>$this->auth->id,
                'description' => '确认到达',
                'created_at' => time(),
                'updated_at' => time(),
            ]);
            $this->success('操作成功',[]);
        }else{

            $this->error('该订单无法操作');
        }
    }

    /*
    * 订单确认
    */
    public function verifyorder()
    {
        $detail=RoleCheck::role($this->auth->id, 'companion');
        if (!$id = input('id')) {
            $this->error('请选择订单');
        }
        Db::startTrans();
        $result = \app\admin\model\Order::where('id', $id)->where('is_reach', '=', 1)->where('order_status', '=', 1)->where('riderid', '=', $detail['id'])->update(['order_status' => 2,'com_time'=>time()]);
        if ($result == 0) {
            DB::rollback();
            $this->error('该订单无法操作');
        } else {
            //发放佣金
            $log = new Log();
            $loglist = $log->where('order_id', '=', $id)->where('status', '=', 0)->select();
            foreach ($loglist as $k => $v) {
                if ($v['type'] != '平台') {
                    Index::op_money($v['user_id'], $v['money'], 'inc', '分享佣金', $v['type'], $v['role']=='companion'?'订单收益':'我的邀请',$id);
                }
                $log->where('id', '=', $v['id'])->update(['status' => 1]);
            }
            Operations::create([
                'order_id' => $id,
                'action' => '订单确认',
                'user_id' =>$this->auth->id,
                'description' => '订单确认',
                'created_at' => time(),
                'updated_at' => time(),
            ]);
            DB::commit();
            $this->success('操作成功',[]);
        }

    }

    public function order_info()
    {
        if (!$id = input('id/d')) {
            $this->error('请选择订单');
        }
        $info = \app\admin\model\Order::where('id', $id)->field('is_reach,order_status,goodtype,id,name,phone,message,address,goodname,goodimage,amount')->find();
        if(!$info){
            $this->error('订单不存在');
        }
        if($info['order_status']==1){
            $info['order_status']=$info['is_reach'];
        }
        $info['goodtype'] = $info['goodtype'] == 0 ? '服务' : '陪伴师';
        $this->success('操作成功', $info);
    }

}

